<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="highQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading"
				  @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="150" sortable>
			</el-table-column>
            <el-table-column prop="sn" label="编号" width="150" sortable>
            </el-table-column>
			<el-table-column prop="state" label="状态" width="150" sortable>
                <template scope="scope">
                    <span style="color: green" v-if="scope.row.state==0">正常</span>
                    <span style="color: red" v-else-if="scope.row.state==-1">停用</span>
                    <span style="color: gray" v-else>未知</span>
                </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="经理" width="150" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="150" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
						   :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加和修改对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<!--
					prop="name" ，如果当前表单项需要验证，必须要加
				 -->
				<el-form-item label="名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">停用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="经理">
					<el-select v-model="saveForm.manager" value-key="id" placeholder="请选择">
						<!--
							v-for="item in cities" - 循环每一个员工对象
							:label="item.username" - 指定要显示哪一个值
							:value="item.value" - 用于点击提交时候传递到后端的数据
							当你绑定的是对象的时候，value-key="id"必须，id是manager对象【员工】的id属性
						-->
						<el-option
								v-for="item in managers"
								:label="item.username"
								:value="item">
							<span style="float: left">{{ item.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上级部门">
					<el-cascader v-model="saveForm.parent"
							:options="deptTree"
							:props="{ checkStrictly: true,label:'name' , value:'id' }"
							clearable>
						<!--
							:options="deptTree"   -  集合
							label:'name'  - 要显示的内容
							value:'id' - 要传递到数据
						-->
					</el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'

	export default {
		data() {
			return {
				filters: {
                    keyword: ''				//高级查询的关键字
				},
				departments: [],			// then中，成功之后赋值
				totals: 0, 					// then中，成功之后赋值
                currentPage: 1,				// 单击事件：handleCurrentChange()
				pageSize:5,					// 直接写死的
				listLoading: false,			//列表显示忙等框
				sels: [],					//批量删除时保存已经选中的对象
                title: "",					//添加和修改的对话框动态显示
				managers:[],  				//保存所有的经理 = 员工
				deptTree: [],				//保存所有的父部门【parent_id=null】和所有子部门

				//编辑模态框模型数据
				saveFormVisible: false,
				saveLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
                    sn: [ //prop属性
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ]
				},
				//添加和修改界面数据清空
				saveForm: {
					id: null,
					name: '',
					sn:"",
					state: 0,
					manager : null,
					parent : null
				}
			}
		},
		methods: {
		    //分页时点击页码时触发
			handleCurrentChange(val) {
				this.currentPage = val;            //改变当前页
				this.getDepartments();
			},

			//高级查询
			highQuery(){
                this.currentPage = 1;            //每次点击高级查询都将当前页设置为1
                this.getDepartments();
            },

			//获取部门列表
			getDepartments() {
				let para = {
					currentPage: this.currentPage,  //分页_当前页
                    pageSize:this.pageSize,         //分页_每页显示的条数
                    keyword: this.filters.keyword   //高级查询的关键字
				};
				this.listLoading = true;            //显示忙等框

                this.$http.post("/department",para)
                    .then(res=>{
                        //1.去掉忙等框
                        this.listLoading = false;
                        //2.给模型数据departments赋值
                        this.departments = res.data.data;
                        //3.给模型数据totals赋值
                        this.totals = res.data.totals;
                    })
                    .catch(res=>{
                        alert("系统错误");
                    })
			},

			//删除 //http://localhost:8080/department/1   --  delete
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => { //点确认执行里面的代码
					this.listLoading = true;
                    let para = "/department/"+row.id;
                    this.$http.delete(para).then(res=>{//删除成功
                        //1.关闭忙等框
                        this.listLoading = false;
                        if(res.data.success){
                            //2.提示删除成功
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //如果删除的当前页只有一条数据的时候：就应该放当前页 = 当前页-1
                            if(this.currentPage>1 && (this.totals-1)%this.pageSize==0){
                                this.currentPage = this.currentPage - 1;
                            }
                            this.getDepartments();//3.重新加载数据
                        }else{
                            this.$message({
                                message: res.data.msg,
                                type: 'error'
                            });
						}
                    }).catch(res=>{ //如果出现跨域问题，连接后端服务器问题，传参错误
                        alert("系统错误");
                    })
				}).catch(() => {

				});
			},

			//显示编辑界面
			handleEdit: function (index, row) {
				this.title = "编辑";
                this.saveForm = Object.assign({}, row); //做回显  -  克隆

				//想办法将父部门的id获取出来  ： /2/5/8   -   [2,5]
				//this.saveForm.parent = [2,5];
                let dirPath = row.dirPath; 				// /2/5/8
                let arr = dirPath.split("/");			//["","2","5","8"]
				//直接转成数值型的数据
				let res = arr.slice(1,arr.length-1).map(Number);	//["2","5"]
				/*for(let i=0;i<res.length;i++){			//[2,5]
                    res[i] = parseInt(res[i]);
				}*/

				this.saveForm.parent = res;
				//加载所有的经理
				this.getManagers();
				//加载所有的上级部门
				this.getDeptTree(row.id);
                this.saveFormVisible = true; //显示对话框
            },

			//显示新增界面
			handleAdd: function () {
                this.title = "添加";
                this.saveForm = {
                    id: '',
                    name: '',
                    sn:'',
                    state: 0,
                    manager : null,
                    parent : null
				};
                //加载所有的经理
                this.getManagers();
                //加载所有的上级部门
                this.getDeptTree(this.saveForm.id);
                this.saveFormVisible = true;
            },

			//点击新增和修改的提交按钮时触发的方法
			saveSubmit: function () {
                //所有的ref属性 其中的 ref="saveForm" 进行验证
                this.$refs.saveForm.validate((valid) => {
					if (valid) { //如果验证成功  - 才执行if里面的代码
						this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
							this.saveLoading = true; //打开忙等框
							let para = Object.assign({}, this.saveForm);//将数据克隆给空对象，并将对象赋值给para变量

							if(para.parent){
                                //上一级部门传值的格式：[2],[2,5] ,我们后端接收的时候 Departmrent对象
                                //{"id",2},{"id",5} -> parent对象 = Departmrent对象
                                //处理parent对象传值
                                let arr = para.parent;
                                let id = arr[arr.length-1]
                                para.parent = {"id":id}
							}

                            this.$http.put("/department",para).then(res=>{
                                this.saveLoading = false;//关闭忙等框
								if(res.data.success){
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['saveForm'].resetFields();//重置对话框
                                    this.saveFormVisible = false;//关闭对话框
                                    this.getDepartments();//重新加载数据
								}else{
                                    this.$message({
                                        message: res.data.msg,
                                        type: 'error'
                                    });
								}
							}).catch(res=>{
							    alert("系统异常，请稍后重试!");
							})
						});
					}
				});
			},

			//批量删除时获取选中的对象
			selsChange: function (sels) {
				this.sels = sels;//会获取选中的对象
			},

			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);// [1,2,5]

				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

					this.$http.patch("/department",ids).then(res=>{
                        this.listLoading = false;
                        if(res.data.success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.currentPage = 1;
                            this.getDepartments();
						}else{
                            this.$message({
                                message: res.data.msg,
                                type: 'error'
                            });
						}
					}).catch(res=>{
					    alert("系统错误")
					});
				}).catch(() => {

				});
			},

			//加载所有的员工【经理】
			getManagers(){
			    this.$http.get("/employee").then(res=>{
			        if(res){
                        this.managers = res.data;
                    }
				})
			},

			//加载部门树[一级部门以及所属的二级部门]
            getDeptTree(id){
			    if(id==""){
			        id=0;
				}
                this.$http.get("/department/deptTree/"+id).then(res=>{
                    if(res){
                        this.deptTree = res.data;
                    }
                })
            }
		},
		mounted() { //页面一加载就调用此方法
            this.getDepartments();
		}
	}

</script>

<style scoped>

</style>